/*!
 * The modal level
 * Version: 1.0.0
 * Modify: 
 * Date: 
 */
(function(){
	var ctx = '',
	$wrap = $('#assetsStatistics'),
	BSS = $('#backSections'),
	backSection = $('#BackSection'),
	BackCalendar = $('#BackCalendar'),//显示日历数据容器
	BSC = $('#BackSectionCount'),
	resetDate = false,
	newdate = new Date(),
	setToday = {
		y: newdate.getFullYear(),
		m: newdate.getMonth()+1,
		d: newdate.getDate()
	},
	json_data = '';//存储提取出来的数据
	var opts = {
		widgetClass: 'calendar-content',
		disableClass: 'state-disabled',//禁用状态
		otherClass: 'other-month', //其它月
		defaultClass: 'state-default', //日期默认状态
		hoverClass: 'state-hover',//鼠标划过状态
		activeClass: 'state-active',//当前日期高亮状态
		curClass: 'state-current',//当前日期高亮状态
		checkClass: 'check-back-day',//查看当前日回款数据
		dayNames: ['\u65e5','\u4e00','\u4e8c','\u4e09','\u56db','\u4e94','\u516d'],//星期
		monthUpper:  ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
		monthNames: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]//月份
	};
	
	//回款日期查询
	function dateBackSection(m,y){
		var setMonths = m - 1;
		var setYears = y;
		$.ajax({
			dataType: 'json',
			url: ctx+'/queryRepayDate.do',
			type: 'POST',
			beforeSend: function() {
				$('.load32-bss').remove();
				$('.err-bss').remove();
				BSS.append('<div class="load32-bss"></div>')
			},
			success: function(data) {
				$('.load32-bss').remove();
				$('.err-bss').remove();
				if(!(data.minRepayDate == '' || data.minRepayDate == null || data.minRepayDate == 'undefined')){
					var _minDate = Util.strDate(data.minRepayDate).format('yyyy/M');
					var _maxDate = Util.strDate(data.maxRepayDate).format('yyyy/M');
					
					BackCalendar.attr('data-min',data.minRepayDate);
					BackCalendar.attr('data-max',data.maxRepayDate);
					generateDateHTML(setMonths,setYears,_minDate,_maxDate);
				};
			},
			error: function() {
				$('.load32-bss').remove();
				$('.err-bss').remove();
				BSS.append('<div class="err-bss">文件加载出错，请重试!</div>')
			}
		});
	};
	function generateDateHTML(setMonths,setYears,_minDate,_maxDate){
		var curDate = new Date(setYears+'/'+(setMonths+1)+'/'+1).format('yyyy/M');
		var btnPrev = '<div class="button icon-Prev '+(curDate == _minDate ? opts.disableClass : '')+'">\u4e0a\u6708</div>';
		var btnNext = '<div class="button icon-Next '+(curDate == _maxDate ? opts.disableClass : '')+'">\u4e0b\u6708</div>';
		var namesY = '<span class="year">'+setYears+'\u5E74</span>';
		var MM = opts.monthNames[setMonths];
		var namesM = '<span class="month">'+ (MM < 10 ? '0'+MM : MM)+'\u6708</span>';
		var headerMonthYear = btnPrev + namesY + namesM + btnNext;
		var html = '<div class="'+opts.widgetClass +'">';
		html += '<div class="head">'+headerMonthYear+'</div>';
		html += '<ul class="week-entry">';
		for (var cols = 0; cols < 7; cols++) {
			html += '<li>' + opts.dayNames[cols] + '</li>';
		};
		html += '</ul>';
		var getMonthDay = Util.yMonthCheck(setMonths, setYears);
		var getFullDate = new Date(setYears, setMonths, 1);
		var getFirstDay = getFullDate.getDay();
		getFirstDay = (getFirstDay == 0 && getFullDate) ? 7 : getFirstDay;
		var prevMonth = setMonths == 0 ? 11 : setMonths - 1;
        var prevYear = prevMonth == 11 ? setYears - 1 : setYears;
        var prevDays = Util.yMonthCheck(prevMonth, prevYear);
		var count = 0;
		html += '<ul class="days-entry">';
		for (var rows = 0; rows < (getFirstDay+getMonthDay<=35?35:42); rows++) {
			if (rows < getFirstDay) {
				if(getFirstDay < 7){
					html += '<li class="'+opts.otherClass+'">'+(prevDays-getFirstDay+rows+1)+'</li>';
				};
			} else if (rows >= getFirstDay + getMonthDay) {
				++count;
				html += '<li class="'+opts.otherClass+'">'+count+'</li>';
			} else {
				var curM = setMonths+1;
				var curD = rows-getFirstDay+1;
				var getCurDate = new Date(setYears+'/'+curM+'/'+curD).format('yyyy/MM/dd');
				var stateClass = opts.defaultClass;
				getCurDate < newdate.format('yyyy/MM/dd') ? stateClass = opts.disableClass : '';
				getCurDate == newdate.format('yyyy/MM/dd') ? stateClass = (opts.defaultClass+' '+opts.curClass) : '';
				html += '<li class="'+stateClass+'" data-date="'+getCurDate+'"><b>'+curD+'</b><span class="icons payment-date" style="display:none"></span></li>';
			}
		};
		html += '</ul>';
		html += '</div>';
		BackCalendar.html(html);
		isRun(setMonths,setYears);
	};
	function isRun(setMonths,setYears){
		var itemList = BackCalendar.find('.days-entry li');
		var itemList2 = BackCalendar.find('.week-entry li');
		var prev = BackCalendar.find('.head .icon-Prev');
		var next = BackCalendar.find('.head .icon-Next');
		var prevYear,prevMonth,nextYear,nextMonth;
		itemList.height(itemList.width());
		itemList.css("line-height",itemList.height()+"px");
		itemList.css("width",(100/7)+"%");
		itemList2.css("width",(100/7)+"%");
		if (setMonths == 0) {
			prevYear = setYears - 1;
			prevMonth = opts.monthNames[11];
		} else {
			prevYear = setYears;
			prevMonth = opts.monthNames[setMonths - 1];
		};
		if (setMonths == 11) {
			nextYear = setYears + 1;
			nextMonth = opts.monthNames[0];
		} else {
			nextYear = setYears;
			nextMonth = opts.monthNames[setMonths + 1];
		};
		prev.click(function(){
			if(!$(this).hasClass(opts.disableClass)){
				dateBackSection(prevMonth,prevYear);
				var getC = new Date(prevYear+'/'+prevMonth);
				var getD = new Date();
				backSectionData(prevYear,prevMonth,getD.getDate(),false);
				resetState();
				//setTimeout(function(){resetState()},200);
			};
		});
		next.click(function(){
			if(!$(this).hasClass(opts.disableClass)){
				dateBackSection(nextMonth,nextYear);
				backSectionData(nextYear,nextMonth,1,true);
				BSC.val(0);
			}
		});
		itemList.click(function(){
			$("#zhezhao").show();
			$("#showTs").show();
			var self = $(this);
			if(!(self.hasClass(opts.otherClass) || self.hasClass(opts.disableClass) || self.hasClass(opts.activeClass))){
				var YMD = Util.strDate(self.attr('data-date'));
				getOtherData(YMD.getFullYear(),(YMD.getMonth()+1),YMD.getDate(),false);
				var index = BackCalendar.find('.days-entry .'+opts.checkClass).index(this);
				if(index < 0){
					var _count = parseInt(self.nextAll('.'+opts.checkClass).attr('data-count'));
					if(isNaN(_count)){
						BSC.val(payArrayTODO().length-1)
					} else {
						BSC.val(_count);
					};
				} else {
					BSC.val(self.attr('data-count'))
				};
				itemList.removeClass(opts.activeClass);
				self.addClass(opts.activeClass);
			};
		}).hover(function(){
			if(!($(this).hasClass(opts.otherClass) || $(this).hasClass(opts.disableClass))){
				$(this).addClass(opts.hoverClass);
			}
		},function(){
			$(this).removeClass(opts.hoverClass)
		});
	};
	
	function backSectionData(_y,_m,_d,resetDate){		
			$.ajax({
				dataType: 'json',
				url: ctx+'/queryRepaySituation.do',
				type: 'POST',
				beforeSend: function() {
					backSection.html('<div class="load32"></div>');
				},
				success: function(data){
					json_data = data;
					getOtherData(_y,_m,_d,resetDate);
				},
				error: function() {
					backSection.html('<div class="fileError" style="color:#c00; display:block">文件加载出错，请重试!</div>');
				}
			})		
	};
	function getOtherData(_y,_m,_d,resetDate){
		var getCurYmd = new Date(_y+'/'+_m+'/'+_d).format('yyyy-MM-dd');
		var json_ylb = json_data.ylbRepayList;
		var json_jfb = json_data.jfbRepayList;
		var json_wyb = json_data.wybRepayList;
		var strMonth = '', html = '';
		var dayLi = BackCalendar.find('.days-entry li');
		var curSta = function (json_data){//加上蓝色小图标
			dayLi.each(function() {
				var self = $(this);
				var getCurDay = new Date(self.attr('data-date')).format('yyyy-MM-dd');
				var bz = self.find('.payment-date');
				if (json_data == getCurDay){
					self.addClass(opts.defaultClass+' '+opts.checkClass);
					self.removeClass(opts.disableClass);
					bz.show();
					if(!self.hasClass(opts.checkClass)){
						self.attr('data-date','');
						bz.remove();
					};
				};
			});
		};
		//月利宝
		var ylbRepayDate = ylbForTotalSum = ylbLoanCounts = ylbRInterest = ylbRPrincipal = 0;
		if(!(json_ylb == ''||json_ylb == 'undefined'||json_ylb == null)){
			$.each(json_ylb, function(index, ylb) {
				var getRepayDate = ylb.repayDate;
				curSta(getRepayDate);//加上蓝色小图标
				if(getCurYmd == getRepayDate){
					ylbRepayDate = getRepayDate; //回款日期
					ylbForTotalSum = ylb.forTotalSum; //月收本息
					ylbRInterest = ylb.repayInterest; //利息
					ylbRPrincipal = ylb.repayPrincipal; //本金
					ylbLoanCounts = ylb.loanCounts; //项目数
				};
			});
		}
		//季发宝
		var jfbRepayDate = jfbForTotalSum = jfbLoanCounts = jfbRInterest = jfbRPrincipal = 0;
		if(!(json_jfb == ''||json_jfb == 'undefined'||json_jfb == null)){
			$.each(json_jfb, function(index, jfb) {
				var getRepayDate = jfb.repayDate;
				curSta(getRepayDate);//加上蓝色小图标
				if(getCurYmd == getRepayDate){
					jfbRepayDate = getRepayDate; //回款日期
					jfbForTotalSum = jfb.forTotalSum; //月收本息
					jfbRInterest = jfb.repayInterest; //利息
					jfbRPrincipal = jfb.repayPrincipal; //本金
					jfbLoanCounts = jfb.loanCounts; //项目数
				};
			});
		}
		//稳盈宝
		var wybRepayDate = wybForTotalSum = wybLoanCounts = wybRInterest = wybRPrincipal = 0;
		if(!(json_wyb == ''||json_wyb == 'undefined'||json_wyb == null)){
			$.each(json_wyb, function(index, wyb) {
				var getRepayDate = wyb.repayDate;
				curSta(getRepayDate);//加上蓝色小图标
				if(getCurYmd == getRepayDate){
					wybRepayDate = getRepayDate; //回款日期
					wybForTotalSum = wyb.forTotalSum; //月收本息
					wybRInterest = wyb.repayInterest; //利息
					wybRPrincipal = wyb.repayPrincipal; //本金
					wybLoanCounts = wyb.loanCounts; //项目数
				};
			});
		}
		
		html += '<div class="back-news">';
		html += '<a href="javascript:;" class="scon icon-Prev" data-text="查看上一个回款项目"></a>';
		if(getCurYmd == ylbRepayDate || getCurYmd == jfbRepayDate || getCurYmd == wybRepayDate){
			var setCurDate;
			if(getCurYmd == ylbRepayDate){
				setCurDate = ylbRepayDate
			} else if(getCurYmd == jfbRepayDate){
				setCurDate = jfbRepayDate
			} else{
				setCurDate = wybRepayDate
			};
			var gd = Util.strDate(setCurDate);
			for(var i in opts.monthUpper){
				strMonth = opts.monthUpper[gd.getMonth()]
			};
			html += '<dl>';
			html += '<dt><span class="m">'+strMonth+'月</span><span class="d">'+gd.getDate()+'</span></dt>';
			html += '<dd><table><tr>';
			html += '<td><p>回款日期 '+gd.format('MM月dd日')+'</p>';
			if(ylbLoanCounts > 0){
				html += '<p>月利宝收益 <em>¥'+(ylbRInterest).toFixed(2)+'</em> 回收本金 <em>¥'+(ylbRPrincipal).toFixed(2)+'</em></p>';
			};
			if(jfbLoanCounts > 0){
				html += '<p>季发宝收益 <em>¥'+(jfbRInterest).toFixed(2)+'</em> 回收本金 <em>¥'+(jfbRPrincipal).toFixed(2)+'</em></p>';
			};
			if(wybLoanCounts > 0){
				html += '<p>稳盈宝收益 <em>¥'+(wybRInterest).toFixed(2)+'</em> 回收本金 <em>¥'+(wybRPrincipal).toFixed(2)+'</em></p>';
			};
//			if(ylbLoanCounts > 0){
//				html += ' 月利宝项目<a href="investmentRecords.session.action" class="r5">'+ylbLoanCounts+'</a>个</p>';
//			};
//			if(jfbLoanCounts > 0){
//				html += ' 季发宝项目<a href="investmentRecords.session.action" class="r5">'+jfbLoanCounts+'</a>个</p>';
//			};
//			if(wybLoanCounts > 0){
//				html += ' 稳盈宝项目<a href="investmentRecords.session.action" class="r5">'+wybLoanCounts+'</a>个</p>';
//			};
			html += '</td></tr></table></dd>';
			html += '</dl>';
		} else {
			html += '<div class="noPaymentRecord" style="display:block">没有回款记录</div>';
		};
		html += '<a href="javascript:;" class="scon icon-Next" data-text="查看下一个回款项目"></a>';
		html += '</div>';
		backSection.html(html);
		backSection.find('dl').animate({top:5,opacity:0.5},300).animate({top:0,opacity:1},600);
		showOtherData(json_data,getCurYmd,resetDate);			
	}
	function showOtherData(json_data,getCurYmd,resetDate){
		var prevPay = backSection.find('.icon-Prev');
		var nextPay = backSection.find('.icon-Next');
		var dLi = BackCalendar.find('.days-entry');
		var payArray = payArrayTODO();
		prevPay.click(function(){
			if(!prevPay.hasClass('disabled')){
				var PCount = parseInt(BSC.val());
				PCount--;
				if(PCount >= 0){
					//alert(1);
					var newD = new Date(payArray[PCount]);
					backSectionData(newD.getFullYear(),(newD.getMonth()+1),newD.getDate(),false);
					BSC.val(PCount);
					dLi.find('li').removeClass(opts.activeClass);
					dLi.find('.state-date-'+PCount).addClass(opts.activeClass);
				} else {
					var nMonth = Util.strDate(getCurYmd);
					var _py = nMonth.getFullYear();
					var _pm = nMonth.getMonth();
					if (_pm == 0) {
						_py = _py - 1;
						_pm = opts.monthNames[11];
					} else {
						_py = _py;
						_pm = opts.monthNames[_pm - 1];
					};
					dateBackSection(_pm,_py);
					backSectionData(_py,_pm,1,false);
					resetState();
					//setTimeout(function(){resetState()},100);
				};
			}
		});
		nextPay.click(function(){
			if(!nextPay.hasClass('disabled')){
				var NCount = parseInt(BSC.val());
				NCount++;
				if(payArray.length > NCount){
					var newD = new Date(payArray[NCount]);
					backSectionData(newD.getFullYear(),(newD.getMonth()+1),newD.getDate(),false);
					BSC.val(NCount);
					dLi.find('li').removeClass(opts.activeClass);
					dLi.find('.state-date-'+NCount).addClass(opts.activeClass);
				} else {
					var nMonth = Util.strDate(getCurYmd);
					var _ny = nMonth.getFullYear();
					var _nm = nMonth.getMonth();
					if (_nm == 11) {
						_ny = _ny + 1;
						_nm = opts.monthNames[0];
					} else {
						_ny = _ny;
						_nm = opts.monthNames[_nm + 1];
					};
					dateBackSection(_nm,_ny);
					//backSectionData(setToday.y,setToday.m,setToday.d,true);
					backSectionData(_ny,_nm,1,true);
					BSC.val(0);
				};
			}
		});
		if(payArray.length != 0){
			var minD = BackCalendar.attr('data-min');
			var maxD = BackCalendar.attr('data-max');
			var payA = Util.strDate(payArray[0]);
			if(payA.format('yyyy/M') == Util.strDate(minD).format('yyyy/M')){
				if(BSC.val() == 0){
					prevPay.addClass('disabled');
				} else {
					prevPay.removeClass('disabled');
				};
			};
			if(Util.strDate(payArray[payArray.length - 1]).format('yyyy/M') == Util.strDate(maxD).format('yyyy/M')){
				if(BSC.val() == payArray.length - 1){
					nextPay.addClass('disabled');
				} else {
					nextPay.removeClass('disabled');
				};
			};
			if(resetDate == true){
				dLi.find('li').removeClass(opts.activeClass);
				dLi.find('.state-date-'+BSC.val()).addClass(opts.activeClass);
				var y = payA.getFullYear();
				var m = payA.getMonth()+1;
				var d = payA.getDate();
				getOtherData(y,m,d,false);
				backSection.show();
			}
		}
	};
	function payArrayTODO(){
		var dayLi = BackCalendar.find('.days-entry .'+opts.checkClass);
		var array = [];
		dayLi.each(function(index) {
			var self = $(this);
			var nd = self.attr('data-date');
			if(nd != ''){
				array.push(nd);
				self.addClass('state-date-'+index);
				self.attr('data-count',index);
			}
		});
		return array;
	};
	function resetState(){
		var payArray = payArrayTODO();
		var len = 0;
		if(payArray.length > 0){
			len = payArray.length-1
		} else {
			len = 0
		};
		var newD = Util.strDate(payArray[len]);
		getOtherData(newD.getFullYear(),(newD.getMonth()+1),newD.getDate(),false);
		backSection.show();
		BSC.val(len);
		var dLi = BackCalendar.find('.days-entry');
		dLi.find('li').removeClass(opts.activeClass);
		dLi.find('.state-date-'+len).addClass(opts.activeClass);
	};
	//回款记录
	dateBackSection(setToday.m,setToday.y);
	backSectionData(setToday.y,setToday.m,setToday.d,true);
})();
